<template>
  <div>
    <el-form size="small" label-width="140px" ref="form" :model="obj">
      <el-card shadow="hover" v-for="(item, index) in obj.family" :key="index" class="family">
        <div class="button">
          <el-button @click="handleAdd(item)" type="warning" icon="el-icon-document-copy" circle></el-button>
          <el-button
            v-show="index !== 0"
            @click="handleDelete(index)"
            type="danger"
            icon="el-icon-delete"
            circle
          ></el-button>
        </div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" :prop="`family[${index}].name`">
              <el-input v-model="item.name" placeholder="请输入姓名" clearable></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="item.remark" type="textarea" :rows="2" placeholder="请输入备注" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="与承包方代表关系" :prop="`family[${index}].relation`">
              <el-input v-model="item.relation" placeholder="请输入与承包方代表关系" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    list: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      obj: {
        family: [{ name: null, relation: null, remark: null }]
      }
    }
  },
  watch: {
    list: {
      handler(newVal, oldVal) {
        if (newVal && newVal.length > 0) this.obj.family = newVal
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    handleDelete(index) {
      this.obj.family.splice(index, 1)
    },
    handleAdd(item) {
      this.obj.family.push(JSON.parse(JSON.stringify(item)))
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          return this.$emit('submit', this.obj.family)
        } else {
          return false
        }
      })
    },
    clearValidate() {
      this.$refs.form.clearValidate()
    }
  }
}
</script>

<style lang="scss" scoped>
.family {
  margin-bottom: 10px;
  position: relative;
  ::v-deep .el-card__body {
    padding: 15px 20px 0 20px;
  }
  ::v-deep .el-card__header {
    border-bottom: none !important;
  }
  .button {
    position: absolute;
    right: 10px;
    bottom: 10px;
    z-index: 999;
  }
}
</style>
